const util = require("../../../utils/util")

function inArray(arr, key ,val){
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i
        }
    }
    return -1
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return (`00${bit.toString(16)}`).slice(-2)
    }
  )
  return hexArr.join('')
}
function utf8ByteToUnicodeStr(utf8Bytes) {
  var unicodeStr = "";
  for (var pos = 0; pos < utf8Bytes.length;) {
    var flag = utf8Bytes[pos];
    var unicode = 0;
    if ((flag >>> 7) === 0) {
      unicodeStr += String.fromCharCode(utf8Bytes[pos]);
      pos += 1;

    } else if ((flag & 0xFC) === 0xFC) {
      unicode = (utf8Bytes[pos] & 0x3) << 30;
      unicode |= (utf8Bytes[pos + 1] & 0x3F) << 24;
      unicode |= (utf8Bytes[pos + 2] & 0x3F) << 18;
      unicode |= (utf8Bytes[pos + 3] & 0x3F) << 12;
      unicode |= (utf8Bytes[pos + 4] & 0x3F) << 6;
      unicode |= (utf8Bytes[pos + 5] & 0x3F);
      unicodeStr += String.fromCharCode(unicode);
      pos += 6;

    } else if ((flag & 0xF8) === 0xF8) {
      unicode = (utf8Bytes[pos] & 0x7) << 24;
      unicode |= (utf8Bytes[pos + 1] & 0x3F) << 18;
      unicode |= (utf8Bytes[pos + 2] & 0x3F) << 12;
      unicode |= (utf8Bytes[pos + 3] & 0x3F) << 6;
      unicode |= (utf8Bytes[pos + 4] & 0x3F);
      unicodeStr += String.fromCharCode(unicode);
      pos += 5;

    } else if ((flag & 0xF0) === 0xF0) {
      unicode = (utf8Bytes[pos] & 0xF) << 18;
      unicode |= (utf8Bytes[pos + 1] & 0x3F) << 12;
      unicode |= (utf8Bytes[pos + 2] & 0x3F) << 6;
      unicode |= (utf8Bytes[pos + 3] & 0x3F);
      unicodeStr += String.fromCharCode(unicode);
      pos += 4;

    } else if ((flag & 0xE0) === 0xE0) {
      unicode = (utf8Bytes[pos] & 0x1F) << 12;
      ;
      unicode |= (utf8Bytes[pos + 1] & 0x3F) << 6;
      unicode |= (utf8Bytes[pos + 2] & 0x3F);
      unicodeStr += String.fromCharCode(unicode);
      pos += 3;
    } else if ((flag & 0xC0) === 0xC0) { //110
      unicode = (utf8Bytes[pos] & 0x3F) << 6;
      unicode |= (utf8Bytes[pos + 1] & 0x3F);
      unicodeStr += String.fromCharCode(unicode);
      pos += 2;
    } else {
      unicodeStr += String.fromCharCode(utf8Bytes[pos]);
      pos += 1;
    }
  }
  return unicodeStr;
}

var app = getApp()
Page({
    data:{
        devices:[],
        _discoveryStarted: false,
        connected: false,
        chs: [],
        name: "",
        deviceid:"",
    },
    onLoad(){
      // this.openBluetoothAdapter()

      //测试全局参数设置
      // var app = getApp()
      // this.setData({
      //   connected:app.globalData.sensor_connected,
      //   name:'test_sensor',
      // })
    },
    //用于测试接收滚动数据控件
    test_data(){
      var that = this
      const data = {}
      const idx = inArray(this.data.chs, 'uuid', 'cyan')
      setInterval(function(){
        console.log('excute')
        let data_type = 'Cytan'
        let valueStr = 'sgabbabsb'
        if (idx === -1) {
          data[`chs[${that.data.chs.length}]`] = {
            dataType: data_type,
            value: valueStr
          }
        } else {
          data[`chs[${idx}]`] = {
            dataType: data_type,
            value: valueStr
          }
        }

        that.setData(data)
      },1000)
    },
    
    onUnload(){
      //关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源
      //在这调用的话，离开页面就会断开蓝牙连接
      // this.closeBluetoothAdapter()
    },
    openBluetoothAdapter(){
        wx.openBluetoothAdapter({
            success: (res) => {
                console.log('openBluetoothAdapter success', res)
                this.startBluetoothDevicesDiscovery()
            },
            fail: (res) => {
                console.log('openBluetoothAdapter failed')
                if (res.errCode === 10001) {
                    wx.showModal({
                      title: '错误',
                      content: '未找到蓝牙设备, 请打开蓝牙后重试。',
                      showCancel: false
                    })
                    wx.onBluetoothAdapterStateChange(function (res) {
          
                      if (res && res.available) {
                        this.startBluetoothDevicesDiscovery()
                      }
                    })
                  }
            },
            complete: (res) => {},
          })
    },
    getBluetoothAdapterState() {
        wx.getBluetoothAdapterState({
          success: (res) => {
            console.log('getBluetoothAdapterState', res)
            if (res.discovering) {
              this.onBluetoothDeviceFound()
            } else if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          }
        })
      },
    //开始扫描
    startBluetoothDevicesDiscovery(){
        if (this._discoveryStarted) {
            return
        }
        this._discoveryStarted = true
        console.log("startBluetoothDevicesDiscovery")
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            services: ["C100"], 
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success',res)
                this.onBluetoothDeviceFound()
            },
            fail: (res) => {
                console.log('startBluetoothDevicesDiscovery failed',res);
            },
            complete: (res) => {},
          })
    },
    stopBluetoothDevicesDiscovery(){
        wx.stopBluetoothDevicesDiscovery({
            success: (res) => {
                console.log('stopBluetoothDevicesDiscovery success',res);
            },
            fail: (res) => {
                console.log('stopBluetoothDevicesDiscovery failed', res);
            },
            complete: (res) => {
                this._discoveryStarted = false
            },
          })
    },
    onBluetoothDeviceFound(){
        console.log('onBluetoothDeviceFound')
        wx.onBluetoothDeviceFound((res) => {
            res.devices.forEach(device => {
              if (!device.name && !device.localName) {
                return
              }
              const foundDevices = this.data.devices
              const idx = inArray(foundDevices, 'deviceId', device.deviceId)
              const data = {}
              if (idx === -1) {
                data[`devices[${foundDevices.length}]`] = device
              } else {
                data[`devices[${idx}]`] = device
              }
              this.setData(data)
            })
          })
    },
    
    closeBluetoothAdapter() {
        wx.closeBluetoothAdapter()
        this._discoveryStarted = false
  },
  //连接
  createBLEConnection(e){
    this.stopBluetoothDevicesDiscovery()
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    console.log('连接的设备id ',deviceId)
    console.log('连接的设备名 ',name)

    wx.showLoading({
      title: 'connecting',
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success: () => {
        console.log("连接成功")
        this.setData({
          connected: true,
          name: name,
          deviceId: deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      },
      complete(){
        wx.hideLoading()
      }
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            console.log(res.services[i].uuid)
            // if (res.services[i].uuid === '2344C100-7994-1CCA-B98B-00FFD0B3CA8A'){
            //   this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            // }else if (res.services[i].uuid === '180A'){
            //   this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            // }
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            // return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
          if (item.properties.read) {
            console.log('读特征值uudid:',item.uuid)
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            console.log('写征值uudid:',item.uuid)
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            console.log('write')
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            console.log('通知的特征值uudid:',item.uuid)
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      // console.log('收到特征uuid:',characteristic.characteristicId)
      // console.log('收到的ori数据:',characteristic.value)
      console.log('收到的数据:',ab2hex(characteristic.value))
      var byteArray = new Int8Array(characteristic.value)
      var valueStr = ab2hex(characteristic.value)
      var data_type = ''
      if (characteristic.characteristicId == '00002A29-0000-1000-8000-00805F9B34FB') {
        //设备信息
        data_type = '设备信息'
        valueStr = utf8ByteToUnicodeStr(byteArray)
      }else if (characteristic.characteristicId == '00002A27-0000-1000-8000-00805F9B34FB') {
        data_type = '硬件版本号'
        valueStr = utf8ByteToUnicodeStr(byteArray)
      }else if (characteristic.characteristicId == '00002A26-0000-1000-8000-00805F9B34FB') {
        data_type = '固件版本号'
        valueStr = utf8ByteToUnicodeStr(byteArray)
      }else if (characteristic.characteristicId == '2344C102-7994-1CCA-B98B-00FFD0B3CA8A') {
        let byte1 = byteArray[0]
        let byte2 = byteArray[1]
        if (byte1 == -1 && byte2 == -2) {
          let byte3 = byteArray[2]
          if (byte3 == 7) {
            data_type = '电池信息'
            let batteryVoltage = (byteArray[5]<<8 | byteArray[6]);
            valueStr = "电量值:"+String(batteryVoltage)
          }else if (byte3 == 52) {
            data_type = '设备定时状态'
            
          }

        }
      }
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          dataType: data_type,
          value: valueStr
        }
      } else {
        data[`chs[${idx}]`] = {
          dataType: data_type,
          value: valueStr
        }
      }
      wx.showToast({
        title: '收到数据',
      })
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue(dataBuffer) {
    // 向蓝牙设备发送一个0x00的16进制数据
    // const buffer = new ArrayBuffer(1)
    // const dataView = new DataView(buffer)
    // // eslint-disable-next-line
    // dataView.setUint8(0, Math.random() * 19| 0)
    console.log(dataBuffer)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: dataBuffer,
      success(res) {
        console.log('writeBLECharacteristicValue: 成功', res.errMsg)
      },
      fail() {
        console.log('writeBLECharacteristicValue: 失败')
      },
      complete() {
        console.log('writeBLECharacteristicValue: 结束')
      }
    })
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getConnectedDevice(){
    wx.getConnectedBluetoothDevices({
      services: ['2344C100-7994-1CCA-B98B-00FFD0B3CA8A','0000180A-0000-1000-8000-00805F9B34FB'],
      success(res){
        console.log(res)
      }
    })
  },
  sendReplyEcgCommand(){
    this.writeBLECharacteristicValue(util.sendAckCommand())
  },
})